/*
 * Created by CZJ on July 19, 2019.
 * @description 图片上传组件
 */
import React, { PureComponent } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet,
  Platform,
} from 'react-native';
import ImagePicker from 'react-native-yiautos-image-picker';
import Permissions from 'react-native-permissions';
import _ from 'lodash';
import YiautosUpgrader from 'react-native-yiautos-upgrader';

import { Dialog } from '~/components';
import { adapt } from '~/utils/ScreenAdapter';
import ImageGallery from '../ImageGallery';
import { Toast } from '../index';
import PropTypes from 'prop-types';

const propTypes = {
  imageCount: PropTypes.number,
  quality: PropTypes.number,
  cropWidth: PropTypes.number,
  isCrop: PropTypes.bool,
  title: PropTypes.string,
  showCropCircle: PropTypes.bool,
  onChange: PropTypes.func,
  source: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
};

const defaultProps = {
  imageCount: 9,
  quality: 50,
  cropWidth: 280,
  title: '上传图片',
  isCrop: false,
  showCropCircle: false,
  source: [],
  onChange: e => null,
};

class YiUpload extends PureComponent {
  static propTypes = propTypes;

  static defaultProps = defaultProps;

  options = {
    imageCount: 1,
    quality: 50,
    isCrop: !!this.props.isCrop,
  };

  constructor(props) {
    super(props);
  }

  deleteImage = index => {
    const { source, onChange } = this.props;
    const modifiedSource = [...source];
    modifiedSource.splice(index, 1);
    onChange && onChange(modifiedSource);
  };

  uploadImage = () => {
    const {
      onChange,
      imageCount,
      quality,
      isCrop,
      showCropCircle,
      cropWidth,
      source,
    } = this.props;
    let sourceCopies = [...source];
    let isIOS = Platform.OS === 'ios';
    Permissions.check('photo')
      .then(res => {
        return new Promise((resolve, reject) => {
          if (!['authorized'].includes(res)) {
            Permissions.request('photo').then(response => {
              resolve(response);
            });
          } else {
            resolve(res);
          }
        });
      })
      .then(result => {
        return new Promise((resolve, reject) => {
          if (!['authorized'].includes(result)) {
            return Dialog.show({
              title: '提示',
              content: (
                <View style={{ alignItems: 'center' }}>
                  <Text>宜买车联盟需要访问您的相册</Text>
                </View>
              ),
              onClose: Dialog.hide,
              onConfirm: isIOS
                ? Permissions.openSettings
                : YiautosUpgrader.openSettings,
            });
          } else {
            resolve();
          }
        });
      })
      .then(() => {
        return ImagePicker.asyncShowImagePicker({
          imageCount,
          quality,
          isCrop: imageCount === 1 && isCrop,
          showCropCircle: imageCount === 1 && isCrop && showCropCircle,
          CropW: cropWidth,
        });
      })
      .then(result => {
        const pickedImages = result.map(item => item.uri || item.original_uri);
        const returnedImages = _.uniq([...sourceCopies, ...pickedImages]);
        onChange && onChange(returnedImages);
      })
      .catch(e => {
        //Toast.fail('选择图片失败!');
      });
  };

  formatSource = source => {
    console.log('解析传来的图片 ==>', source);
    if (_.isArray(source)) {
      return source.map(item => {
        if (_.isObject(item) && (item.uri || item.original_uri)) {
          return { uri: item.uri || item.original_uri };
        } else if (_.isString(item)) {
          return {
            uri: item,
          };
        } else {
          Toast.fail('解析图片失败!');
          return [];
        }
      });
    } else {
      return [{ uri: source }];
    }
  };

  render() {
    const { title, imageCount, source } = this.props;
    const displaySource = this.formatSource(source);
    console.log('display', displaySource);
    return (
      <View style={styles.container}>
        <Text>{title}</Text>
        <View style={styles.content}>
          {(source.length === 0 || source.length < imageCount) && (
            <TouchableOpacity style={styles.button} onPress={this.uploadImage}>
              <Image
                source={require('../../assets/setting/upload_image.png')}
                style={{ height: adapt(64), width: adapt(64) }}
              />
            </TouchableOpacity>
          )}
          {displaySource.map((src, index) => (
            <TouchableOpacity
              onPress={() => this.gallery.open(index, displaySource)}
              key={src.uri}
            >
              <Image source={src} style={styles.image} />
              <TouchableOpacity
                onPress={this.deleteImage.bind(this, index)}
                style={{
                  position: 'absolute',
                  top: adapt(8),
                  right: adapt(-8),
                  height: adapt(32),
                  width: adapt(32),
                }}
              >
                <Image
                  source={require('../../assets/setting/delete.png')}
                  style={{ width: adapt(16), height: adapt(16) }}
                />
              </TouchableOpacity>
            </TouchableOpacity>
          ))}
        </View>
        <ImageGallery ref={ref => (this.gallery = ref)} />
      </View>
    );
  }
}
/*
 * @param title { String } 上传图片的标题
 * @param onChange { Function } data => YourHandler; 上传后的回调
 * @param maxLimit { Number } 最大图片显示数
 * @param value { Array } 默认图片
 */
export default YiUpload;

const styles = StyleSheet.create({
  container: {
    padding: adapt(16),
  },
  content: {
    flexDirection: 'row',
    width: '100%',
    flexWrap: 'wrap',
  },
  button: {
    marginTop: adapt(16),
    height: adapt(64),
    width: adapt(64),
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: adapt(16),
  },
  image: {
    height: adapt(64),
    width: adapt(64),
    marginRight: adapt(16),
    marginTop: adapt(16),
  },
});
